﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using ExplorerPlus.DomainObjects;
using ExplorerPlus.PluginsInterface;
using ExplorerPlus.Plugins.Common;

namespace ExplorerPlus.Plugins.Books
{
    public partial class BooksItemDetailView : UserControl, IItemDetailViewPlugin
    {
        //Control object responsible for rating movie titles.  
        //Workaround: project cannot dynamically build this custom control type
        //                      after using New Project wizard; the control instance is created and sited at runtime instead of 
        //                      adding to design surface.  
        internal ExplorerPlus.Controls.RatingPickerControl ratingPickerControl =
            new ExplorerPlus.Controls.RatingPickerControl();

        Item book;
        bool blnHasChanges = false;

        public BooksItemDetailView()
        {
            InitializeComponent();
            this.webBrowser1.AllowNavigation = false;
            this.webBrowser1.AllowWebBrowserDrop = false;
            this.webBrowser1.WebBrowserShortcutsEnabled = false;
        }

        #region IItemDetailViewPlugin Members

        UserControl IItemDetailViewPlugin.ItemDetailView
        {
            get { return this; }
        }

        bool IItemDetailViewPlugin.HasChanges
        {
            get { return blnHasChanges; }
            set { blnHasChanges = value; }
        }

        void IItemDetailViewPlugin.Initialize(Item item)
        {
            book = item;
            txtTitle.Text = book.ItemName;
            txtFilePath.Text = book.FilePath;
            txtAuthor.Text = book.GetItemPropertyValue((int)BookFields.Author);
            //txtCustomerReviews.Text = book.GetItemPropertyValue((int)BookFields.TotalCustomerReviews);
            txtEdition.Text = book.GetItemPropertyValue((int)BookFields.Edition);
            txtEditorialReviews.Text = book.GetItemPropertyValue((int)BookFields.EditorialReviews);
            txtISBN.Text = book.GetItemPropertyValue((int)BookFields.ISBN);
            txtListPrice.Text = book.GetItemPropertyValue((int)BookFields.ListPrice);
            txtNoofPages.Text = book.GetItemPropertyValue((int)BookFields.NoOfPages);
            txtPublicationDate.Text = book.GetItemPropertyValue((int)BookFields.PublicationDate);
            txtPublisher.Text = book.GetItemPropertyValue((int)BookFields.Publisher);
            //txtRating.Text = book.GetItemPropertyValue((int)BookFields.Rating);
            txtSalesRank.Text = book.GetItemPropertyValue((int)BookFields.SalesRank);
            pictureBox1.ImageLocation = book.GetItemPropertyValue((int)BookFields.LargeImage);
            if (webBrowser1.Document != null)
            {
                webBrowser1.Document.Body.InnerHtml =
                    "<html><body  style='font-family:Tahoma; font-size=10pt'>"
                        + book.GetItemPropertyValue((int)BookFields.EditorialReviews)
                        + "</body></html>";
            }
            else
            {
                webBrowser1.DocumentText =
                    "<html><body  style='font-family:Tahoma; font-size=10pt'>"
                    + book.GetItemPropertyValue((int)BookFields.EditorialReviews)
                    + "</body></html>";
            }
            SetRating();
            RegisterValueChangesEvent(this);
        }

        bool IItemDetailViewPlugin.Validate()
        {
            if (txtTitle.Text == string.Empty || txtTitle.Text.Trim().Length == 0)
            {
                MessageBox.Show("Please enter book title.");
                return false;
            }

            return true;
        }

        Item IItemDetailViewPlugin.GetItem()
        {
            SetItem();
            return book;
        }

        private void SetItem()
        {
            book.ItemName = txtTitle.Text;
            book.FilePath = txtFilePath.Text;
            PluginHelper.ExtractValueList(book, (int)BookFields.Author, txtAuthor.Text);
            book.SetItemPropertyValue((int)BookFields.Edition, txtEdition.Text);
            book.SetItemPropertyValue((int)BookFields.EditorialReviews, txtEditorialReviews.Text);
            book.SetItemPropertyValue((int)BookFields.ISBN, txtISBN.Text);
            book.SetItemPropertyValue((int)BookFields.ListPrice, txtListPrice.Text);
            book.SetItemPropertyValue((int)BookFields.NoOfPages, txtNoofPages.Text);
            book.SetItemPropertyValue((int)BookFields.PublicationDate, txtPublicationDate.Text);
            book.SetItemPropertyValue((int)BookFields.Publisher, txtPublisher.Text);
            book.SetItemPropertyValue((int)BookFields.Rating, ratingPickerControl.CurrentRating.ToString());
            book.SetItemPropertyValue((int)BookFields.SalesRank, txtSalesRank.Text);
            //book.SetItemPropertyValue((int)BookFields.TotalCustomerReviews, txtCustomerReviews.Text);
            if (book.GetItemPropertyValue((int)BookFields.Category) == "")
            {
                book.AddItemProperty((int)BookFields.Category, "General");
            }
        }

        Item IItemDetailViewPlugin.Store()
        {
            SetItem();
            blnHasChanges = false;
            if (book.ItemId == -1)
            {
                if (book.GetItemPropertyValue((int)BookFields.LargeImage).Length > 0)
                {
                    string path = Application.StartupPath + "\\Images\\Books\\" +
                        System.IO.Path.GetFileName(
                        book.GetItemPropertyValue((int)BookFields.LargeImage));
                    pictureBox1.Image.Save(path);
                    book.SetItemPropertyValue((int)BookFields.LargeImage, path);
                }
            }
            return book;
        }

        public void DragDropFile(string[] filePath)
        {
            book.FilePath = filePath[0];
            txtFilePath.Text = filePath[0];
        }

        #endregion

        #region IDisposable Members

        void IDisposable.Dispose()
        {
            this.book = null;
            if (!this.webBrowser1.IsDisposed)
            {
                this.webBrowser1.Dispose();
            }
            this.webBrowser1 = null;
            base.Dispose();
        }

        #endregion

        private void lnkVisitPage_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            ExplorerPlus.Plugins.Common.PluginHelper.VisitPage(book.GetItemPropertyValue((int)BookFields.DetailPageUrl));
        }

        private void lnkOpenFile_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            ExplorerPlus.Plugins.Common.PluginHelper.OpenFile(book.FilePath);
        }

        private void lnkOpenDirectory_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            ExplorerPlus.Plugins.Common.PluginHelper.OpenDirectory(book.FilePath);
        }

        private void btnOpen_Click(object sender, EventArgs e)
        {
            if (openFileDialog1.ShowDialog() == DialogResult.OK)
            {
                txtFilePath.Text = openFileDialog1.FileName;
                book.FilePath = openFileDialog1.FileName;
            }
        }

        #region Register form controls editing
        private void RegisterValueChangesEvent(Control ctl)
        {
            if (ctl.HasChildren)
            {
                foreach (Control child in ctl.Controls)
                {
                    RegisterValueChangesEvent(child);
                }
            }
            else
                RegisterControlGenericEvent(ctl);
        }

        private void RegisterControlGenericEvent(Control ctl)
        {
            if (ctl is Label)
                return;
            else if (ctl is TextBox || ctl is ComboBox || ctl is DateTimePicker)
            {
                ctl.TextChanged += new EventHandler(ctl_TextChanged);
                return;
            }
            else if (ctl is RadioButton)
            {
                ((RadioButton)ctl).CheckedChanged += new EventHandler(ctl_TextChanged);
            }
        }

        void ctl_TextChanged(object sender, EventArgs e)
        {
            blnHasChanges = true;
        }
        #endregion

        /// <summary>
        /// Initializes the rating picker control used on this user control.  
        /// </summary>
        /// <remarks>
        /// Called by ListDetails.Load event.  This special initialization code is not required if the 
        /// RatingPickerControl is built and referenced in a separate control library.  
        /// </remarks>
        private void InitRatingPickerControl()
        {
            //create rating picker control object and site it on the parent user control
            this.panel3.Controls.Add(this.ratingPickerControl);
            //set default properties and data binding
            ((System.ComponentModel.ISupportInitialize)this.ratingPickerControl).BeginInit();
            this.ratingPickerControl.Anchor = (System.Windows.Forms.AnchorStyles)(System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right);
            this.ratingPickerControl.BackColor = System.Drawing.Color.Transparent;
            this.ratingPickerControl.Location = new System.Drawing.Point(55, 216);
            this.ratingPickerControl.Name = "RatingPickerControl1";
            this.ratingPickerControl.Size = new System.Drawing.Size(80, 16);
            this.ratingPickerControl.TabIndex = 1;
            ((System.ComponentModel.ISupportInitialize)this.ratingPickerControl).EndInit();
        }

        private void SetRating()
        {
            if (ratingPickerControl != null)
            {
                string rating = book.GetItemPropertyValue((int)BookFields.Rating);
                if (rating != string.Empty || rating != "")
                {
                    double result = -1;
                    if (double.TryParse(rating, out result))
                    {
                        this.ratingPickerControl.CurrentRating = (int)result;
                    }
                }
                else
                {
                    this.ratingPickerControl.CurrentRating = -1;
                }
            }

            string customerRating =
                book.GetItemPropertyValue((int)BookFields.TotalCustomerReviews);

            if (customerRating != string.Empty || customerRating != "")
            {
                this.lblCustomerReviews.Text = "(" + customerRating + ")";
            }
        }

        private void BooksItemDetailView_Load(object sender, EventArgs e)
        {
            //dynamically create rating picker control and site on the form
            InitRatingPickerControl();
        }

    }
}
